package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.DeliveryRecord;
import com.wing.sell.model.entity.DeliveryRecordDetail;
import com.wing.sell.model.entity.FinishedOrder;
import com.wing.sell.model.entity.Order;
import com.wing.sell.model.request.DeliveryRecordForm;
import com.wing.sell.model.response.DeliveryRecordVO;
import com.wing.sell.model.response.OrderSkuDetailSearchVo;
import com.wing.sell.service.DeliveryRecordDetailService;
import com.wing.sell.service.DeliveryRecordService;
import com.wing.sell.service.FinishedOrderService;
import com.wing.sell.service.OrderService;
import com.wing.sell.strategy.AbstractGenerateSelOrderService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Validated
@Api(value = "Admin-交付记录管理", tags = "#/sell/deliveryRecord")
@RestController("deliveryRecordController")
@RequestMapping("sell/admin/deliveryRecord")
@RequiredArgsConstructor
public class DeliveryRecordController {

    private final DeliveryRecordService deliveryRecordService;
    private final DeliveryRecordDetailService deliveryRecordDetailService;
    private final FinishedOrderService finishedOrderService;
    private final OrderService orderService;

    @Autowired
    private AbstractGenerateSelOrderService abstractGenerateOrderService;


    @ApiOperation(value = "查询所有交付记录表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<DeliveryRecordVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
            ,@RequestParam(value = "typeCode",required = false) String typeCode
            ,@RequestParam(value = "code",required = false) String code
            ,@RequestParam(value = "orderCode",required = false) String orderCode
            ,@RequestParam(value = "customerId",required = false) String customerId
            ,@RequestParam(value = "expressCode",required = false) String expressCode
    ) {

        Page<DeliveryRecordVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        params.put("typeCode", typeCode);
        params.put("code", code);
        params.put("customerId", customerId);
        params.put("orderCode", orderCode);
        params.put("expressCode", expressCode);
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }
        IPage<DeliveryRecordVO> list = deliveryRecordService.pageList4app(pg, params);
        if (CollectionUtil.isNotEmpty(list.getRecords())) {
            list.getRecords().forEach(info -> {
//                if (null != info.getSaleOrderId()) {
//                    if (info.getTypeCode().equals(ProductEnum.outTypeEmum.CPC.getCode())) {
//                        FinishedOrder orderServiceById = finishedOrderService.getById(info.getSaleOrderId());
//                        if (ObjectUtil.isNotEmpty(orderServiceById)) {
//                            info.setSaleOrderCode(orderServiceById.getSelCode());
//                        }
//                    } else if (info.getTypeCode().equals(ProductEnum.outTypeEmum.SCDC.getCode())) {
//                        Order byId = orderService.getById(info.getSaleOrderId());
//                        if (ObjectUtil.isNotEmpty(byId)) {
//                            info.setSaleOrderCode(byId.getCode());
//                        }
//                    }
//                }
                //查询总金额和个数
                QueryWrapper<DeliveryRecordDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("delivery_record_id", info.getId());
                queryWrapper.eq("is_deleted",false);
                List<DeliveryRecordDetail> deliveryRecordDetails = this.deliveryRecordDetailService.list(queryWrapper);
                if (CollectionUtil.isNotEmpty(deliveryRecordDetails)) {
                    info.setShipmentQty((long) deliveryRecordDetails.size());
                    BigDecimal count= BigDecimal.ZERO;
                    for (DeliveryRecordDetail deliveryRecordDetail : deliveryRecordDetails) {
                        if (deliveryRecordDetail.getSubtotalAmount()!=null) {
                            count = count.add(deliveryRecordDetail.getSubtotalAmount());
                        }
                    }
                    info.setSubtotalAmount(count);
                }

            });
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加交付记录表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody DeliveryRecordForm deliveryRecordForm) {
        try {
            deliveryRecordService.add(deliveryRecordForm);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            return JsonResult.fail("添加失败" + e.getMessage());
        }
    }


    @ApiOperation(value = "修改交付记录表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(DeliveryRecordForm.Update.class) DeliveryRecordForm deliveryRecordForm) {
        DeliveryRecord deliveryRecord = deliveryRecordService.getById(deliveryRecordForm.getId());
        if (deliveryRecord == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(DeliveryRecord.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(deliveryRecordForm, deliveryRecord, copyOptions);
        if (deliveryRecordService.updateById(deliveryRecord)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除交付记录表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deliveryRecordsId", value = "交付记录表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long deliveryRecordsId) {
        if (deliveryRecordService.removeById(deliveryRecordsId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @GetMapping("/inventoryList")
    public PageResult<DeliveryRecordVO> inventoryList(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
    ) {
        Page<DeliveryRecordVO> pg = new Page<>(page, limit);
        Map params = new HashMap();

        IPage<DeliveryRecordVO> list = deliveryRecordService.pageDeliveryRecordList(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/getSaleOrderInfo")
    public JsonResult getSaleOrderInfo(Long selOrderId) {
        Map<String, Object> params = new HashMap<>();

        if (selOrderId != null) {
            params.put("selOrderId", selOrderId);
        }

        List<DeliveryRecordVO> list = null;
        try {
            list = deliveryRecordService.saleOrderList(params);
        } catch (Exception e) {
            throw new RuntimeException("销售订单查询失败：" + e.getMessage());
        }

        if (list.isEmpty()) {
            return JsonResult.success("订单无数据");
        }

        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询-交付记录详情", notes = "详情")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/detail/{id}")
    public JsonResult getDetail(@PathVariable("id") Long id) {
        DeliveryRecordForm form = deliveryRecordService.getDetailBy(id);
        return JsonResult.success(form);
    }


    @ApiOperation(value = "查询订单中物料信息", notes = "查询-订单sku")
    @PostMapping("/getSkuInfoByType")
    public JsonResult<List<OrderSkuDetailSearchVo>> getSkuInfoByType(
            @RequestParam("orderId") Long orderId,
            @RequestParam("type") String type,
            @RequestParam(value = "warehouseId", required = false) Long warehouseId
    ) {
        List<OrderSkuDetailSearchVo> searchVos = abstractGenerateOrderService.getSelOrderList(type, orderId,warehouseId);
        return JsonResult.success(searchVos);
    }


    @ApiOperation(value = "添加交付记录(新-公共)", notes = "添加-交付记录new")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addDeliveryInfo")
    public JsonResult addDeliveryInfo (@RequestBody DeliveryRecordForm deliveryRecordForm) {
        if(StrUtil.isEmpty(deliveryRecordForm.getTypeCode())){
            return JsonResult.fail("typeCode未传入");
        }
        Integer i = abstractGenerateOrderService.generateSelOrder(deliveryRecordForm.getTypeCode(), deliveryRecordForm);
        if (i>0) {
            return JsonResult.success();
        }else{
            return JsonResult.fail("common.fail");
        }
    }

}
